package com.youlu.campus.service.ca.impl;

import com.google.common.collect.Lists;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.res.CaRecommendRes;
import com.youlu.campus.service.activity.impl.ActivityPayButtonConfigService;
import com.youlu.campus.service.cache.CacheActivityService;
import com.youlu.campus.service.cache.CacheCaGroupInfoService;
import com.youlu.campus.service.cache.CacheCaInfoService;
import com.youlu.campus.service.cache.CachePayConfigService;
import com.youlu.campus.service.platform.PlatformConfigService;
import com.youlu.campus.service.visitor.VisitorUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.youlu.campus.service.activity.impl.ActivityPayConfigService.activityPayUrl;

@Slf4j
@Service
public class CaRecommendService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ActivityPayButtonConfigService activityPayButtonConfigService;

    @Autowired
    private CacheCaGroupInfoService cacheCaGroupInfoService;

    @Autowired
    private CacheCaInfoService cacheCaInfoService;

    @Autowired
    private VisitorUserService visitorUserService;

    @Autowired
    private CacheActivityService cacheActivityService;

    @Autowired
    private CachePayConfigService cachePayConfigService;

    @Autowired
    private PlatformConfigService platformConfigService;


    /**
     * 待领取证书
     * @param currentUser
     */
    public Map<String,Object> caRecommend(UserPO currentUser){
        String currentUserId = currentUser.getId();
        String currentPlatform = currentUser.getCurrentPlatform();
        Map<String,Object> mapType = new HashMap<>(3);
        mapType.put("platform",currentPlatform);
        Map<String, List<CertificateActivityConfig>> activityMap = activityPayButtonConfigService.availActivity();
        if(MapUtils.isEmpty(activityMap)){
            mapType.put("count",0);
            mapType.put("list",new ArrayList<>());
            return mapType;
        }
        List<CaRecommendRes> list = Lists.newArrayList();
        List<String> activityIdList = new ArrayList<>(activityMap.size());
        activityMap.forEach((activityId,item)->{
            PayConfigPage payConfigPage = cachePayConfigService.findByActivityId(activityId);
            if(Objects.isNull(payConfigPage)|| !payConfigPage.getReceiveCa()){
                return;
            }
            activityIdList.add(activityId);
            item.stream().forEach(certificateActivityConfig -> {
                buildCaRecommend(list,certificateActivityConfig);
            });
        });
        if(CollectionUtils.isEmpty(list)){
            mapType.put("count",0);
            mapType.put("list",new ArrayList<>());
            return mapType;
        }
        Query  query = new Query();
        query.addCriteria(Criteria.where("openId").is(currentUser.getOpenId()));
        query.addCriteria(Criteria.where("activityId").in(activityIdList));
        List<ActivityUserRecord> activityUserRecordList = this.mongoTemplate.find(query, ActivityUserRecord.class);
        if(CollectionUtils.isEmpty(activityUserRecordList)){
            mapType.put("count",0);
            mapType.put("list",new ArrayList<>());
            return mapType;
        }
        log.info("当前用户 - > {} 来源平台 - >{} ",currentUserId,currentPlatform);
        Set<String> activityUserSet = activityUserRecordList.stream().map(user -> user.getActivityId() + "-" + user.getTaskBizType()).collect(Collectors.toSet());
        query = new Query();
        if(currentPlatform.equals("h5")){
            List<String> mobiles = visitorUserService.findSameMobiles(currentUserId);
            if (!org.springframework.util.CollectionUtils.isEmpty(mobiles)) {
                Criteria criteria = new Criteria();
                criteria.orOperator(Criteria.where("accountInfoId").is(currentUserId), Criteria.where("mobile").in(mobiles));
                query.addCriteria(criteria);
            }
        }else{
            query.addCriteria(Criteria.where("accountInfoId").is(currentUserId));
        }
        query.addCriteria(Criteria.where("activityId").in(activityIdList));
        query.addCriteria(Criteria.where("status").nin(Arrays.asList("0","9","6","7")));
        List<OrderInfo> orderList = this.mongoTemplate.find(query, OrderInfo.class);
        if(CollectionUtils.isEmpty(orderList)){
            List<CaRecommendRes> newList = list.stream().filter(caRecommendRes -> activityUserSet.contains((caRecommendRes.getActivityId() + "-" + caRecommendRes.getTaskBizType()))).collect(Collectors.toList());
            mapType.put("count",newList.size());
            mapType.put("list",newList);
            return mapType;
        }
        Set<String> buyCertificateTypeSet = orderList.stream().map(orderInfo -> orderInfo.getActivityId()+"-"+orderInfo.getTaskBizType()).collect(Collectors.toSet());
        List<CaRecommendRes> newList = list.stream().filter(caRecommendRes -> !buyCertificateTypeSet.contains((caRecommendRes.getActivityId() + "-" + caRecommendRes.getTaskBizType()))).collect(Collectors.toList());
        List<CaRecommendRes> collect = newList.stream().filter(caRecommendRes -> activityUserSet.contains((caRecommendRes.getActivityId() + "-" + caRecommendRes.getTaskBizType()))).collect(Collectors.toList());
        if(currentPlatform.equals("h5")){
            newList.forEach(caRecommendRes -> {
                String activityId = caRecommendRes.getActivityId();
                PayConfigPage payConfigPage = cachePayConfigService.findByActivityId(activityId);
                ActivityInfo activityInfo = cacheActivityService.findById(activityId);
                caRecommendRes.setIncentivesEndTime(activityInfo.getIncentivesEndTime());
                caRecommendRes.setWechatPayUrl(platformConfigService.getBizFrontPayDomain()+String.format(activityPayUrl, activityId, activityInfo.getThemeColor(), payConfigPage.getAppId()));
                caRecommendRes.setShowCountDown(payConfigPage.getShowCountDown());
                caRecommendRes.setCountdownColor(payConfigPage.getCountdownColor());
                List<PayButtonConfigPage> payButtonConfigList = payConfigPage.getPayButtonConfigList();
                if(CollectionUtils.isNotEmpty(payButtonConfigList)){
                    PayButtonConfigPage payButtonConfig = payButtonConfigList.stream().filter(payButtonConfigPage -> payButtonConfigPage.getActivityId().equals(caRecommendRes.getActivityId()) && payButtonConfigPage.getCaType().equals(caRecommendRes.getTaskBizType())).findFirst().orElse(null);
                    if(Objects.nonNull(payButtonConfig)){
                        caRecommendRes.setUserInfoCertificateShow(payButtonConfig.getUserInfoCertificateShow());
                    }
                }
            });
        }
        mapType.put("count",collect.size());
        mapType.put("list",collect);
        return mapType;
    }

    private void buildCaRecommend(List<CaRecommendRes> list,CertificateActivityConfig certificateActivityConfig){
        String caType = certificateActivityConfig.getCaType();
        String activityId = certificateActivityConfig.getActivityId();
        CaGroupInfo caGroupInfo = cacheCaGroupInfoService.findByActivityIdAndTaskBizType(activityId, caType);
        if(Objects.isNull(caGroupInfo)){
            return;
        }
        List<CaInfo> caInfoList = cacheCaInfoService.findByGroupIdAndLevel(caGroupInfo.getId(), "");
        if(CollectionUtils.isNotEmpty(caInfoList)){
            CaInfo caInfo = caInfoList.get(0);
            CaRecommendRes caRecommendRes = new CaRecommendRes();
            caRecommendRes.setActivityId(activityId);
            caRecommendRes.setCaGroupName(caGroupInfo.getName());
            if(ArrayUtils.isEmpty(caInfo.getCertificateImages())){
                caRecommendRes.setCertificateImage(caInfo.getCertificateImage());
            }else{
                caRecommendRes.setCertificateImage(caInfo.getCertificateImages()[0]);
            }
            caRecommendRes.setTaskBizType(caType);
            caRecommendRes.setCaInfoId(caInfo.getId());
            list.add(caRecommendRes);
        }

    }
}
